﻿using System.Linq;

namespace HelloWorldBll.Helper
{
    /// <summary>
    /// 共用Ip工具类
    /// </summary>
    public static class IpHelper
    {
        #region 获得用户IP
        /// <summary>
        /// 获得用户IP
        /// </summary>
        public static string GetUserIp()
        {
            string ip;
            string[] temp;
            var isErr = false;
            ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null ? System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
            if (ip.Length > 15)
                isErr = true;
            else
            {
                temp = ip.Split('.');
                if (temp.Length == 4)
                {
                    foreach (var t in temp.Where(t => t.Length > 3))
                    {
                        isErr = true;
                    }
                }
                else
                    isErr = true;
            }

            return isErr ? "1.1.1.1" : ip;
        }
        #endregion
    }
}
